<template>
  <div class="mx-auto px-4 py-4" w="360px">
    <Spin :spinning="loading">
      <Form
        @finish="onLogin"
        :model="formData"
        :rules="rules"
        ref="formRef"
        autocomplete="off"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <FormItem label="用户名" name="usernameOrMobile">
          <Input
            placeholder="请输入用户名"
            v-model:value="formData.usernameOrMobile"
          />
        </FormItem>
        <FormItem label="密码" name="password">
          <Input
            type="password"
            v-model:value="formData.password"
            placeholder="请输入密码"
          />
        </FormItem>
        <FormItem name="verificationCode" label="验证码">
          <Input
            v-model:value="formData.verificationCode"
            placeholder="请输入验证码"
            :maxlength="4"
          >
            <template #addonAfter>
              <img
                :src="imageCodeSrc"
                alt="图片验证码"
                h="30px"
                class="-ml-11px -mr-11px"
                @click.stop="getExtImageCode"
              />
            </template>
          </Input>
        </FormItem>

        <div class="text-center">
          <Button class="w-full" html-type="submit">登录</Button>
        </div>
      </Form>
    </Spin>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { Button, Spin, Form, FormItem, Input, message } from 'ant-design-vue';
import { sendMessage } from 'webext-bridge';
import {
  EXT_CLICK_USER_LOGIN,
  EXT_GET_IMAGE_CODE,
  EXT_SET_USER_TOKEN,
} from '~/events';
import { makeEncry } from '~/utils';
import { storageToken } from '~/logic';

const loading = ref(false);
const imageCodeSrc = ref<string>();
const $emits = defineEmits(['finish']);
const formData = reactive<{
  verificationCodeId?: string;
  usernameOrMobile: '';
  password: '';
  verificationCode: '';
}>({
  usernameOrMobile: '',
  password: '',
  verificationCode: '',
  verificationCodeId: '',
});
const rules = {
  usernameOrMobile: [
    {
      required: true,
      message: '请输入用户名',
      validator: (rule: any, value: any) => {
        if (!value) {
          return Promise.reject('请输入用户名');
        }
        return Promise.resolve();
      },
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
    },
  ],
  verificationCode: [
    {
      required: true,
      message: '请输入验证码',
    },
  ],
};

const labelCol = { span: 5 },
  wrapperCol = { span: 19 };

async function getExtImageCode() {
  try {
    const resp = (await sendMessage(EXT_GET_IMAGE_CODE, {})) as any;
    if (resp.code === 200) {
      imageCodeSrc.value = resp.data.imageBase64;
      formData.verificationCodeId = resp.data.id;
    } else {
      message.warn('获取图片验证码失败');
    }
  } catch (error) {
    message.warn('获取图片验证码失败');
    console.log(error);
  }
}
getExtImageCode();

async function onLogin(params: any) {
  loading.value = true;
  try {
    params.password = makeEncry(params.password);
    const resp = (await sendMessage(EXT_CLICK_USER_LOGIN, {
      ...params,
      verificationCodeId: formData.verificationCodeId,
    })) as any;

    if (resp.code === 200) {
      const token = resp.data.tokenValue;
      message.success('登录成功');
      sendMessage(EXT_SET_USER_TOKEN, { token });
      $emits('finish');
      setTimeout(() => {
        storageToken.value = token;
        loading.value = false;
      }, 500);
    } else {
      const msg = resp.msg;
      message.warn(msg);
      setTimeout(() => {
        storageToken.value = null;
        sendMessage(EXT_SET_USER_TOKEN, { token: null });
        loading.value = false;
      }, 500);
    }
  } catch (err) {
    loading.value = false;
    console.log(err);
  }
}
</script>
